#include <iostream>
#include <string>
#include <vector>

#include <cstdlib>
#include <cassert>
#include <pthread.h>
#include <unistd.h>

using namespace std;
const int NUM = 10;

class ThreadData
{
public:
    int number;
    pthread_t tid;
    char namebuffer[64];
};

class ThreadReturn
{
public:
    int exit_code;
    int exit_result;
};

void *start_routine(void *arg) // 这个函数被多个线程进入，是可重入函数
{
    sleep(1);
    ThreadData *td = static_cast<ThreadData *>(arg);
    int cnt = 10;
    while (cnt)
    {
        cout << "new thread name:" << td->namebuffer << " cnt: " << cnt-- << " cnt地址:" << &cnt << endl;
        sleep(1);
    }

    ThreadReturn *tr = new ThreadReturn();
    tr->exit_code = 0;
    tr->exit_result = td->number;
    return (void *)1; // 右值
}

int main()
{
    // 1.创建一批线程
    vector<ThreadData *> threads; // 用于线程保存线程的数据
    for (int i = 0; i < NUM; i++)
    {
        ThreadData *td = new ThreadData();
        td->number = i;
        snprintf(td->namebuffer, sizeof(td->namebuffer), "%s:%d", "thread", i + 1);
        pthread_create(&td->tid, NULL, start_routine, td);
        threads.push_back(td);
    }
    for (auto &thread : threads)
    {
        cout << "creat thread: " << thread->namebuffer << ":" << thread->tid << " success" << endl;
    }
    sleep(5);

    // 线程取消，这里取消前5个线程
    // 如果线程被取消了，线程的退出码是-1(宏: PTHREAD_CANCELED)
    for (int i = 0; i < threads.size() / 2; i++)
    {
        pthread_cancel(threads[i]->tid);
        cout << "cancel thread: " << threads[i]->namebuffer << " success" << endl;
    }

    // 创建时候循环创建，等待的时候一次性等待
    for (auto &thread : threads)
    {

        void *ret = nullptr;
        int n = pthread_join(thread->tid, &ret); // void **retp, *retp = ret , *ret = 值
        assert(n == 0);
        (void)n;

        cout << "join " << thread->namebuffer << " success exitcode:" << (long long)ret << endl;
        delete thread;
    }

    cout << "main thread quit" << endl;
    return 0;
}